import {createContext,useContext, useEffect,useState} from 'react';
import {useLocalStorage} from './use-storage'; // useLocalStorage 封装了操作 localStorage 的能力

const Context = createContext();


export const TransProvider = ({ i18n, children }) => {
    console.log('TransProvider 组件初始化------');
  if (!i18n) {
    throw new Error('No i18n provide.');
  }
  const  [lang, setLang] = useLocalStorage('lang', undefined);
  const [locales, setLocales] = useLocalStorage('locales', undefined);

  console.log('数据初始化   lang:',lang,'locales:',locales);

  useEffect(() => {
    let currentLang = lang;
    console.log('currentLang:',currentLang);
    if (!lang) {
      const { navigator } = window;
      currentLang = navigator.language;
      setLang(currentLang)
      console.log('useEffect : 设置 lang,currentLang:',currentLang);

    }

    if (!locales ||
      !locales.data ||
      !locales.date ||
      !locales.lang ||
      locales.lang !== currentLang ||
      Date.now() - locales.date > 86400000
      ) {
        
      setLocales({data: i18n[currentLang], lang: currentLang,
         date: Date.now()})
        console.log('useEffect : 设置 locales：',locales);
    }
    
  })

  console.log('---locales.data',locales.data);
  const getMessages = () => locales.data


  const setNewLang = newLang => {
    setLang(newLang)
    setLocales({data: i18n[newLang], lang: newLang, date: Date.now()})
  }

  if (!locales) return <div>Loading...</div>
  // setLang('en');
  return (
    <Context.Provider value={{
      lang,
      locales,
      getMessages,
      setNewLang
    }}>
      {children}
    </Context.Provider>
  )
}

export const useI18n = path => {
  const { getMessages }  = useContext(Context)
  return  getMessages(path)
}

export const setLang = () => {
  const { lang, setNewLang } = useContext(Context);
  return [ lang, setNewLang ]
}